package cn.org.itool.ws.framework.netty.channel;

import cn.org.itool.ws.framework.config.NettyProperties;
import cn.org.itool.ws.framework.netty.channel.HttpHeartBeatHandler;
import cn.org.itool.ws.framework.netty.channel.WsAuthChannelInboundHandlerAdapter;
import cn.org.itool.ws.framework.ws.WsServer;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;

public class WsServerInitializer extends ChannelInitializer<SocketChannel> {
    private static final CloseHandler CLOSE_HANDLER = new CloseHandler();

    private static final NettyProperties NETTY_PROPERTIES = WsServer.NETTY_PROPERTIES;

    private static final HeartbeatHandler HEARTBEAT_HANDLER = new HeartbeatHandler();


    private static final WsAuthChannelInboundHandlerAdapter AUTHORIZATION_HANDLER = new WsAuthChannelInboundHandlerAdapter();

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        WebSocketServerProtocolConfig config = WebSocketServerProtocolConfig.newBuilder()
                .websocketPath(NETTY_PROPERTIES.getPath())
                .checkStartsWith(true)
                .dropPongFrames(false)
                .allowExtensions(true).build();
        pipeline.addLast(new WebSocketServerProtocolHandler(config));
        pipeline.addLast(new HttpHeartBeatHandler(NETTY_PROPERTIES.getHttpHeartbeatPath()));
        pipeline.addLast("authorizationHandler", AUTHORIZATION_HANDLER);
        pipeline.addLast( "idleStateHandler", new IdleStateHandler(NETTY_PROPERTIES.getIdleSec(),0,0, TimeUnit.SECONDS));
        pipeline.addLast("heartbeatHandler", HEARTBEAT_HANDLER);
        pipeline.addLast("closeHandler", CLOSE_HANDLER);
    }

}
